package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000152.R;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener;
import com.shwread.http.ActionHelp;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import logic.bean.NewInteractionInfo;
import logic.constants.DefaultConsts;
import logic.util.DateUtil;
import logic.util.ImageLoaderUtil;
import logic.util.Utils;


/**
 * 
 * 活动列表页面
 * @author xuzhijun
 * @date 2015年5月12日下午6:23:06
 */
public class NewInteractionActvListActivity
        extends
        BaseSimpleActivity
        implements
        OnClickListener
{
	private final int                PAGESIZE           = 5;
	
	private Context                  mContext;
	private final int                flag_loadMore      = 2;
	private final int                flag_reload        = 3;
	private final int                flag_noMore        = 4;
	
	private int                      load_flag          = 0;
	private boolean                  isFirstIn          = true;
	//Title
	private TextView                 tvTitle;
	private Button                   btnBack;
	
	private PullToRefreshScrollView  pullToRefreshView;
	private ListView                 listView;
	
	private RelativeLayout           mEnptyView;
	private ActivityAdapter          adapter;
	private List<NewInteractionInfo> actvList;
	private View                     switchView;
	private ImageView                switchImg;
	private AnimationDrawable        switchDrawable;
	private long                     currentPublishTime = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_interaction_activitylist);
		this.mContext = this;
		initView();
		initData();
		
	}
	
	private void initView() {
		//Title		
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		tvTitle.setText(R.string.new_interaction_actvlist);
		btnBack = (Button) findViewById(R.id.common_header_back);
		btnBack.setVisibility(View.VISIBLE);
		btnBack.setOnClickListener(this);
		
		switchView = findViewById(R.id.column_switch_layout);
		switchImg = (ImageView) findViewById(R.id.column_switch_img);
		pullToRefreshView = (PullToRefreshScrollView) findViewById(R.id.activityRefreshView);
		PullToRefreshUtil.initLabel(mContext, pullToRefreshView);
		listView = (ListView) findViewById(R.id.activityListView);
		mEnptyView = (RelativeLayout) findViewById(R.id.emptyView);
	}
	
	private void initData() {
		updateSwitchView(0);
		actvList = new ArrayList<NewInteractionInfo>();
		getActvList(flag_reload);
		
		adapter = new ActivityAdapter();
		listView.setAdapter(adapter);
		pullToRefreshView.setOnRefreshListener(new OnRefreshListener<ScrollView>()
		{
			
			@Override
			public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
				if (refreshView.isHeaderShown())
				{
					getActvList(flag_reload);
				}
				else if (refreshView.isFooterShown())
				{
					getActvList(flag_loadMore);
				}
			}
		});
	}
	
	private void getActvList(int flage) {
		
		switch (flage) {
			case flag_loadMore:
				if (load_flag != flag_noMore)
				{
					currentPublishTime = actvList==null||actvList.isEmpty() ? 0 :actvList.get(actvList.size()-1).getPublishTime();
					this.load_flag = flage;
					ActionHelp.qryTopicActivityList(mContext, currentPublishTime, PAGESIZE, new GetMangerDataHandler());
					PullToRefreshUtil.initLabel(mContext, pullToRefreshView);
				}
				else
				{
					PullToRefreshUtil.setLoadLabel(pullToRefreshView, "没有更多数据了");
					pullToRefreshView.onRefreshComplete();
				}
				
				break;
			case flag_reload:
				PullToRefreshUtil.initLabel(mContext, pullToRefreshView);
				currentPublishTime = 0;
				this.load_flag = flage;
				ActionHelp.qryTopicActivityList(mContext, currentPublishTime, PAGESIZE, new GetMangerDataHandler());
				break;
		}
		
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_back:
				finish();
				break;
		}
	}
	
	/**
	 * @project newInteraction
	 * @description 客户经理获取数据的监听事件
	 * @author zhangnannan
	 * @Time 2015年5月12日 下午4:23:56
	 */
	
	class GetMangerDataHandler
	        extends
	        ObjectHttpResponseHandler<List<NewInteractionInfo>>
	{
		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			pullToRefreshView.onRefreshComplete();
			if (isFirstIn)
			{
				updateSwitchView(-1);
				isFirstIn = false;
			}
		}
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, List<NewInteractionInfo> object, String responseString) {
			if (object != null && object.size() > 0)
			{
				
				if (load_flag == flag_reload)
				{
					actvList.clear();
					actvList.addAll(object);
				}
				else if (load_flag == flag_loadMore)
				{
					actvList.addAll(object);
				}
				if (object.size() < PAGESIZE)
				{
					load_flag = flag_noMore;
				}
				adapter.notifyDataSetChanged();
				updateSwitchView(1);
			}
			else
			{				
				if(load_flag==flag_loadMore){
					PullToRefreshUtil.setLoadLabel(pullToRefreshView, "没有更多了");
				}else{					
					updateSwitchView(2);
				}
				load_flag = flag_noMore;
			}
			pullToRefreshView.onRefreshComplete();
			if (isFirstIn)
			{
				isFirstIn = false;
			}
		}
		
		@Override
		public Type getType() {
			return new TypeToken<List<NewInteractionInfo>>()
			{
			}.getType();
		}
		
	}
	
	private class ActivityAdapter
	        extends
	        BaseAdapter
	{
		
		@Override
		public int getCount() {
			return actvList.size();
		}
		
		@Override
		public Object getItem(int position) {
			return actvList.get(position);
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder;
			if (convertView == null)
			{
				viewHolder = new ViewHolder();
				convertView = LayoutInflater.from(mContext).inflate(R.layout.new_interaction_activitylist_item, listView, false);
				viewHolder.title = (TextView) convertView.findViewById(R.id.activityTitle);
				viewHolder.time = (TextView) convertView.findViewById(R.id.activityTime);
				viewHolder.img = (ImageView) convertView.findViewById(R.id.activityImage);
				viewHolder.shareImg = (ImageView) convertView.findViewById(R.id.activityShareImg);
				convertView.setTag(viewHolder);
			}
			else
			{
				viewHolder = (ViewHolder) convertView.getTag();
			}
			
			final NewInteractionInfo info =  actvList.get(position);
			
			viewHolder.shareImg.setOnClickListener(new OnClickListener()
			{
				
				@Override
				public void onClick(View v) {
					// TODO 分享NewInteractionCenterChoseGroupActivity
					Intent choseGroupIntent = new Intent(NewInteractionActvListActivity.this, NewInteractionCenterChoseGroupActivity.class);
					choseGroupIntent.putExtra(DefaultConsts.INTERACTIONINFO, info);
					NewInteractionActvListActivity.this.startActivity(choseGroupIntent);
				}
			});
			
			if (Utils.isNotEmpty(info.getImageList()))
			{
				ImageLoaderUtil.loadWebUrl(info.getImageList().split(",")[0], viewHolder.img);
				viewHolder.img.setVisibility(View.VISIBLE);
				viewHolder.img.setOnClickListener(new OnClickListener()
				{
					
					@Override
					public void onClick(View v) {
						
						final ArrayList<String> List = new ArrayList<String>();
						for (String url : info.getImageList().split(","))
						{
							List.add(url);
						}
						Intent AtlasSeeIntent = new Intent();
						AtlasSeeIntent.setClass(mContext, NewInteractionAtlasSeeActivity.class);
						AtlasSeeIntent.putExtra(DefaultConsts.NI_ATLASSEE_URL, List);
						AtlasSeeIntent.putExtra(DefaultConsts.FROM_TYPE, DefaultConsts.NI_FROM_WEBURL);
						mContext.startActivity(AtlasSeeIntent);
					}
				});
			}else{
				viewHolder.img.setVisibility(View.GONE);
			}
			viewHolder.title.setText(info.getContent());
			viewHolder.time.setText(DateUtil.getRegionTime(info.getPublishTime()));
			return convertView;
		}
		
	}
	
	private class ViewHolder
	{
		public TextView title, time, commentsCount;
		public ImageView img, shareImg;
	}
	
	/**
	 * 栏目切换加载动画
	 * 
	 * @param flag
	 *            0:加载中，1：加载完成，2: 内容为空 -1：加载失败
	 */
	public void updateSwitchView(int flag) {
		switch (flag) {
			case -1:
				switchView.setVisibility(View.VISIBLE);
				mEnptyView.setVisibility(View.GONE);
				pullToRefreshView.setVisibility(View.GONE);
				if (switchDrawable != null && switchDrawable.isRunning())
				{
					switchDrawable.stop();
				}
				switchImg.setBackgroundResource(R.drawable.home_loading_fail);
				break;
			case 0:
				switchView.setVisibility(View.VISIBLE);
				pullToRefreshView.setVisibility(View.GONE);
				mEnptyView.setVisibility(View.GONE);
				switchImg.setBackgroundResource(R.anim.home_progress);
				switchDrawable = (AnimationDrawable) switchImg.getBackground();
				switchDrawable.start();
				break;
			case 1:
				switchView.setVisibility(View.GONE);
				mEnptyView.setVisibility(View.GONE);
				pullToRefreshView.setVisibility(View.VISIBLE);
				break;
			case 2:
				switchView.setVisibility(View.GONE);
				mEnptyView.setVisibility(View.VISIBLE);
				pullToRefreshView.setVisibility(View.GONE);
				break;
		}
	}
	
}
